﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using H2.NET.Data.Common;
using H2.NET.Business;

namespace H2.NET.Web.Controls
{
    public partial class ControlsAttachment : TaskControl
    {
        #region 属性 AllowUpload(是否允许上传)
        public bool AllowUpload
        {
            get
            {
                return ViewState["AllowUpload"] == null ? true : (bool)ViewState["AllowUpload"];
            }
            set
            {
                ViewState["AllowUpload"] = value;
            }
        }
        #endregion

        #region 属性 AllowDelete(是否允许删除)
        public bool AllowDelete
        {
            get
            {
                return ViewState["AllowDelete"] == null ? true : (bool)ViewState["AllowDelete"];
            }
            set
            {
                ViewState["AllowDelete"] = value;
            }
        }
        #endregion

        #region 属性 FileClass(文件类别)
        public string FileClass
        {
            get
            {
                return ViewState["FileClass"] == null ? "" : (string)ViewState["FileClass"];
            }
            set
            {
                ViewState["FileClass"] = value;
            }
        }
        #endregion

        #region 属性 Process(文件类别)
        public string PProcess
        {
            get
            {
                return ViewState["PProcess"] == null ? "" : (string)ViewState["PProcess"];
            }
            set
            {
                ViewState["PProcess"] = value;
            }
        }
        #endregion

        #region 属性 Step(文件类别)
        public string PStep
        {
            get
            {
                return ViewState["PStep"] == null ? "" : (string)ViewState["PStep"];
            }
            set
            {
                ViewState["PStep"] = value;
            }
        }
        #endregion

        #region 属性 PIncident(文件类别)
        public int PIncident
        {
            get
            {
                return ViewState["PIncident"] == null ? 0 : (int)ViewState["PIncident"];
            }
            set
            {
                ViewState["PIncident"] = value;
            }
        }
        #endregion

        #region 属性 Max(最大上传数量)
        public int Max
        {
            get
            {
                return ViewState["Max"] == null ? 9999 : (int)ViewState["Max"];
            }
            set
            {
                ViewState["Max"] = value;
            }
        }

        public string IsShow { get { return AllowUpload && this.rep_Attachment.Items.Count < Max ? "" : "display:none;"; } }

        #endregion

        #region 属性 FirstFile(第一个文件)
        public string FirstFilePath
        {
            get
            {
                return ViewState["FirstFilePath"] == null ? "" : (string)ViewState["FirstFilePath"];
            }
            set
            {
                ViewState["FirstFilePath"] = value;
            }
        }
        #endregion

        #region 属性 IsHaveAttachment(是否存在附件)
        public bool IsHaveAttachment
        {
            get
            {
                return ViewState["IsHaveAttachment"] == null ? false : (bool)ViewState["IsHaveAttachment"];
            }
            set
            {
                ViewState["IsHaveAttachment"] = value;
            }
        }
        #endregion

        #region 事件 Load (页面)
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                //列表绑定
                Bind();           
            }
        }
        #endregion

        #region 事件 ItemCommand (列表)
        /// <summary>
        /// 
        /// </summary>
        /// <param name="source"></param>
        /// <param name="e"></param>
        protected void rep_Attachment_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Footer)
            {
                //文件上传
                if (e.CommandName == "Upload")
                {
                    RepeaterItem rep = (RepeaterItem)rep_Attachment.Controls[rep_Attachment.Controls.Count - 1];
                    FileUpload fu = (FileUpload)rep.FindControl("File");

                    //如果存在文件的情况
                    if (fu.HasFile)
                    {
                        //文件类型上传限制
                        //string Ext = System.IO.Path.GetExtension(fu.FileName).ToLower();
                        //string[] AllowExt = { ".gif", ".bmp", ".png", ".jpg" };
                        string Ext = System.IO.Path.GetExtension(fu.FileName).ToLower();
                        if (Ext == ".xls")
                        {
                            string errorMsg = "系统不支持上传XLS格式文件，请另存为XLSM或者XLSX格式文件后重试";
                            Anthem.Manager.AddScriptForClientSideEval(string.Format("ShowMessage(\"{0}\", {1});", errorMsg, errorMsg.Length));
                            return;
                        }
                        try
                        {
                            //判断目录是否存在
                            string path = Path.Combine(Util.AppSettings("path"), (string.IsNullOrEmpty(PProcess) ? TaskAPI.Process : PProcess));
                            string date = System.DateTime.Now.ToString("yyyyMMddHHmmssfff");

                            if (!Directory.Exists(path))
                            {
                                Directory.CreateDirectory(path);
                            }

                            //文件保存
                            fu.SaveAs(path + @"\" + date + @"~" + fu.FileName);

                            //记录集保存
                            H2.NET.Business.t_Attachment att = new H2.NET.Business.t_Attachment();
                            att.ID           = date;
                            att.Process      = (string.IsNullOrEmpty(PProcess) ? TaskAPI.Process : PProcess);
                            att.Incident     = (string.IsNullOrEmpty(PProcess) ? TaskAPI.Incident : PIncident);
                            att.Step         = (string.IsNullOrEmpty(PProcess) ? TaskAPI.Step : PStep);
                            att.UserName     = UserAPI.UserName;
                            att.UserFullName = UserAPI.UserFullName;
                            att.Department   = UserAPI.Department;
                            att.Time         = System.DateTime.Now;
                            att.FileName     = fu.FileName;
                            att.FileClass    = FileClass;
                            att.Status       = 1;
                            Storage.Save(Storage.Context1, att);

                            //列表绑定
                            Bind();
                        }
                        catch (Exception)
                        {
                        }
                    }
                }

                //文件删除
                if (e.CommandName == "Delete")
                {
                    (H2.NET.Business.t_Attachment.id == e.CommandArgument).Edit<H2.NET.Business.t_Attachment>(Storage.Context1, o => 
                    {
                        o.Time=System.DateTime.Now;
                        o.Status = 2;
                    });

                    //列表绑定
                    Bind();
                }
            }
        }
        #endregion

        #region 方法 绑定 
        /// <summary>
        /// 
        /// </summary>
        private void Bind()
        {
            Expression exp = new Expression();
            if (string.IsNullOrEmpty(PProcess))
            {
                exp &= H2.NET.Business.t_Attachment.process == TaskAPI.Process;
                exp &= H2.NET.Business.t_Attachment.incident == TaskAPI.Incident;

                if (TaskAPI.Incident <= 0)
                {
                    exp &= H2.NET.Business.t_Attachment.username == UserAPI.UserName;
                }
                if (TaskAPI.Process == "NPL Master Data Application")
                {
                    if (TaskAPI.Step != "Technical Bom" && !TaskAPI.Step.Contains("DMO") && !TaskAPI.Step.Contains("Technical") && !TaskAPI.Step.Contains("PV"))
                    {
                        exp &= H2.NET.Business.t_Attachment.step != "Technical Bom";
                    }
                } 
            }
            else
            {
                exp &= H2.NET.Business.t_Attachment.process == PProcess;
                exp &= H2.NET.Business.t_Attachment.incident == PIncident;
            }

            exp &= H2.NET.Business.t_Attachment.fileClass == FileClass;
            exp &= H2.NET.Business.t_Attachment.status == 1;    

            List<H2.NET.Business.t_Attachment> list = (List<H2.NET.Business.t_Attachment>)exp.List<H2.NET.Business.t_Attachment>(Storage.Context1, new Region(0, 100), H2.NET.Business.t_Attachment.time.Asc);
                
            //加密文件名

            foreach (H2.NET.Business.t_Attachment att in list)
            {
                att.EncryptFileName = Util.Encrypt((string.IsNullOrEmpty(PProcess) ? TaskAPI.Process : PProcess) + @"\" + att.ID + "~" + att.FileName);
            }
            
            FirstFilePath = list.Count > 0 ? Util.AppSettings("path") + (string.IsNullOrEmpty(PProcess) ? TaskAPI.Process : PProcess) + @"\" + list[0].ID + "~" + list[0].FileName : "";
            IsHaveAttachment = list.Count > 0;

            rep_Attachment.DataSource = list;
            rep_Attachment.DataBind();


            //是否禁用删除
            foreach (RepeaterItem rep in rep_Attachment.Items)
            {
                string UserName = ((Label)rep.FindControl("lbl_UserName")).Text.ToString();
                if (AllowDelete && UserName == UserAPI.UserName)
                {
                    ((ImageButton)rep.FindControl("img_Del")).Visible = true;
                }
                else
                {
                    ((ImageButton)rep.FindControl("img_Del")).Visible = false;
                }
            }

            //注册 文件下载 Javascript 事件
            foreach (RepeaterItem ri in rep_Attachment.Items)
            {
                ImageButton ib = (ImageButton)ri.Controls[5];
                ib.Attributes["onclick"] = "FileHandler('" + ResolveUrl("~/FileHandler.ashx") + "?File=" + ib.CommandArgument + "');";
            }
        }
        #endregion
    }
}
